package com.imy.luasupport.bridge;

import android.util.Log;

import com.imy.luasupport.constant.LuaSetting;
import com.imy.luasupport.core.LuaCore;
import com.imy.luasupport.util.LLog;

import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaValue;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import alscript.lua.bridge.util.BridgeRunnable;

/**
 * javaToLua
 */
public class BaseLifeCycle<T> {
  protected Globals mGlobals;
  private T mProxyInterface;

  public BaseLifeCycle(Globals globals) {
    this.mGlobals = globals;
    //获得接口
    Class<?>[] interfaces = getClass().getInterfaces();
    mProxyInterface = (T) Proxy.newProxyInstance(getClass().getClassLoader(), interfaces, new BridgeInvocationHandler(mGlobals, this));
  }

  public T getInterfaces() {
    return (T) mProxyInterface;
  }

  public static class BridgeInvocationHandler implements InvocationHandler {
    private Globals globals;
    private BaseLifeCycle baseLifeCycle;

    public BridgeInvocationHandler(Globals mGlobals, BaseLifeCycle tBaseLifeCycle) {
      this.globals = mGlobals;
      this.baseLifeCycle = tBaseLifeCycle;
    }

    @Override
    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
      //查看是否有bridge标识
      //获取所有的方法
      Method realMethod = baseLifeCycle.getClass().getMethod(method.getName(), method.getParameterTypes());
      Bridge annotation = realMethod.getAnnotation(Bridge.class);
      if (annotation != null) {
        //call
        ExecutorService executorService = LuaCore.get().getExecutorService();
        LuaValue luaValue = globals.get(method.getName());
        executorService.execute(new BridgeRunnable(luaValue,realMethod,objects));
      }
      return null;
    }
  }
}

